import os
import re
import pandas as pd
import numpy as np
# from read_data import get_flow_report
from App.read_data import get_flow_report
# 定义文件路径
SCRIPT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
BASE_DIR = os.path.join(SCRIPT_DIR, "System_of_A")
DATA_DIR = os.path.join(BASE_DIR, "read_and_process_data")
OUTPUT_DIR = os.path.join(DATA_DIR, "Load_and_devicedata")
# 确保输出目录存在
os.makedirs(OUTPUT_DIR, exist_ok=True)


midu_water = 1000 # 水的密度为1000kg/m3
c_water = 4.186 # 水的比热容为4.186kJ/(kg·℃)
# 计算主机的COP（平均）
def calculate_host_COP(start_time,end_time):

    id = 9

    rename_map = {"t_LD_in (℃)": "t_LD_in",# 冷冻水回水温度
                   "t_LD_out (℃)": "t_LD_out",# 冷冻水出水温度
                   "t_w (℃)": "t_w", # 环境温度
                   "d_w (%)": "d_w",# 环境湿度

                   "flow_LD": "flow_LD", # 冷冻水流量
                "function_lsjz":"function",# 冷水主机1的运行状态
                  "Power_lsjz (kW)": "power", # 冷水主机1的功率
                  "Q_lsjz (%)": "Q_lsjz", # 冷水主机1的百分比制冷量，主机值
                  "oriTs":"timestamp"
                  }
    data = get_flow_report(id=id, start_time=start_time, end_time=end_time, rename_map=rename_map)
    # 对数据进行筛选
    data = data[
        (data['t_LD_in'] >= 0) & (data['t_LD_in'] <= 40) &
        (data['t_LD_out'] >= 0) & (data['t_LD_out'] <= 40) &
        (data['t_w'] >= -100) & (data['t_w'] <= 70) &
        (data['d_w'] >= 0) & (data['d_w'] <= 100) &
        (data['flow_LD'] >= 0) & (data['flow_LD'] <= 500) &
        (data['power'] >= 0) & (data['power'] <= 400)
    ]
    
    data['load'] =data['flow_LD']*midu_water*\
            c_water*(data['t_LD_in']-data['t_LD_out'])/3600  # kJ
    data['t_in_diff'] = data['t_LD_in'].diff()   
    data['t_out_diff'] = data['t_LD_out'].diff()
    # 计算实际负荷
    data['real_load'] = data['load'] +(data['t_out_diff']- data['t_in_diff'])*midu_water*c_water*data['flow_LD']/3600
    # 整理数据


    data.to_csv(os.path.join(OUTPUT_DIR, "data_COP.csv"), index=False)
    # 删除load为0的行
    data = data[data['flow_LD']> 0]
    data = data[data['real_load']> 0]
    # 主机的COP（平均）
    host_COP = data['real_load'].sum() / data['power'].sum()
    return host_COP ,data

def calculate_waterSystem_COP(start_time,end_time):

    # 加载水泵数据
    id = 11

    rename_map = {"LD-A1-冷冻泵状态": "pump_function",# 水泵运行状态
                   "LD-A1-冷冻泵功率 (kW)": "pump_power",# 水泵功率
                   "LD-A1-冷冻泵频率反馈 (Hz)": "pump_frequency", # 水泵频率
                   "Q1-流量": "pump_flow",# 水泵流量
                   
                  "oriTs":"timestamp"
                  }
    data_pump = get_flow_report(id=id, start_time=start_time, end_time=end_time, rename_map=rename_map)
    
    # 对数据进行筛选
    data_pump = data_pump[
    #        (data_pump['function'] == 1) &  # 只保留运行状态为1的数据
        (data_pump['pump_power'] > 1) & (data_pump['pump_power'] <= 50) &  # 功率范围筛选
        (data_pump['pump_frequency'] > 0) & (data_pump['pump_frequency'] <= 50) &  # 频率范围筛选
        (data_pump['pump_flow'] > 0) & (data_pump['pump_flow'] <= 250)  # 流量范围筛选
    ]

    # 
    host_COP ,data = calculate_host_COP(start_time,end_time)

    # 合并数据
    data = pd.merge(data, data_pump, on='timestamp', how='inner')

    # 计算水系统总功耗
    data['waterSystem_power'] = data['power'] + data_pump['pump_power']
    
    data.to_csv(os.path.join(OUTPUT_DIR, "data_waterSystem_COP.csv"), index=False)
    # 删除load为0的行
    data = data[data['flow_LD']> 0]
    #data = data[data['real_load']> 0]
    # 计算水系统COP
    waterSystem_COP = data['real_load'].sum() / (data['power'].sum()+data['pump_power'].sum())


    return waterSystem_COP



if __name__ == "__main__":
    start_time = "2025-06-15 00:00:00"
    end_time = "2025-07-01 01:00:00"
    host_COP,_ = calculate_host_COP(start_time, end_time)
    waterSystem_COP = calculate_waterSystem_COP(start_time, end_time)
    print(f"主机平均COP为{host_COP:2f},水系统COP为{waterSystem_COP:2f}")

